package com.firefly.admin.common.annotations.aspect;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import com.firefly.admin.common.annotations.annotation.SensitiveEncrypt;
import com.firefly.admin.common.enums.SensitiveTypeEnum;
import com.firefly.admin.common.utils.SensitiveEncryptUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@NoArgsConstructor
@AllArgsConstructor
@Component
public class SensitiveSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private SensitiveTypeEnum sensitiveType;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        value = SensitiveEncryptUtil.sensitiveEncrypt(value, sensitiveType);
        jsonGenerator.writeString(value);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
        SensitiveEncrypt annotation = property.getAnnotation(SensitiveEncrypt.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
            this.sensitiveType = annotation.type();
            return this;
        }
        return serializerProvider.findValueSerializer(property.getType(), property);
    }
}
